﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Zocono.Infrastructure.Common;
using Zocono.WCS.Domain.DomainRepository;
using Zocono.WCS.Domain.PlcBytesObject;
using Zocono.WCS.Domain.PlcConnectPoolDomain;
using Zocono.WCS.Domain.ProcessModuleDomain;
using Zocono.WCS.Domain.EntityInfo;
using Zocono.WCS.Infrastructure.PlcCommon;
using Zocono.WCS.Infrastructure.ApllicationDto.WCSTaskDto;
using Zocono.WCS.Infrastructure.ApllicationDto.Enums;
using SqlSugar;
using Zocono.WCS.WMSApiDomain.WebApi;
using Newtonsoft.Json;
using Zocono.WCS.Domain.LogDomain;

namespace Zocono.WCS.Domain.EquipmentProcessDomain.PlanarGeneralMessage
{
    /// <summary>
    /// 数量检测
    /// </summary>
    public class CountCheckService : IPlanarGeneralPlcActionProcessService
    {
        private readonly IRedisHelper _IRedisHelper;
        private readonly ILogUtil _LogUtil;
        private readonly IPlcConnectionPool _PlcConnectionPool;
        private readonly IWorkTaskInfoRepository _WorkTaskInfoRepository;
        private readonly IPlcWriteDbInfoRepository _PlcWriteDbInfoRepository;
        private readonly ISnowflake _Snowflake;
        private readonly IPlcConnectionStateInfoRepository _IPlcConnectionStateInfoRepository;
        private readonly IRunLogInfoService _IRunLogInfoService;

        private readonly ITelegramRecordInfoRepository _TelegramRecordInfoRepository;

        public CountCheckService(IRedisHelper iRedisHelper, ILogUtil logUtil, ISnowflake snowflake
            , IPlcConnectionPool plcConnectionPool
            , IWorkTaskInfoRepository workTaskInfoRepository
            , IPlcWriteDbInfoRepository plcWriteDbInfoRepository
            , ITelegramRecordInfoRepository telegramRecordInfoRepository
             , IPlcConnectionStateInfoRepository plcConnectionStateInfoRepository
             , IRunLogInfoService runLogInfoService)
        {
            _IRedisHelper = iRedisHelper;
            _LogUtil = logUtil;
            _PlcConnectionPool = plcConnectionPool;
            _WorkTaskInfoRepository = workTaskInfoRepository;
            _PlcWriteDbInfoRepository = plcWriteDbInfoRepository;
            _Snowflake = snowflake;
            _TelegramRecordInfoRepository = telegramRecordInfoRepository;
            _IPlcConnectionStateInfoRepository = plcConnectionStateInfoRepository;
            _IRunLogInfoService = runLogInfoService;
        }


        public async Task ProcessActionMessageAsync(BytesObjectBase plcActionMessage, BytesObjectBase wcsActionMessage,
            EquipmentDbObject planarEquipmentDbObject/*, BytesObjectBase plcStateMassge*/)
        {
            var plcMessage = plcActionMessage as PlanarGeneralPlcActionBO;//Plc的动作报文
            var wcsMessage = wcsActionMessage as PlanarGeneralWcsActionBO;//Wcs的动作报文
            //var plcStateBo = plcStateMassge as PlcOnLineStateBO;//Plc在线离线报文 没有设备信息
            plcMessage.PalletBarcode = plcMessage.PalletBarcode.Trim();

            PlanarGeneralWriteWcsAction writeBo = null;//写入Plc的报文
            PlcConnectionS7 plcConn = _PlcConnectionPool.S7GetWritePlcConnection(plcMessage.PlcConnectionID);//plc写入连接（不锁定）
            RunLogInfo runLogInfo = new RunLogInfo();
            runLogInfo.ContainerBarcode = plcMessage.PalletBarcode;
            runLogInfo.EquipmentCode = plcMessage.EquipmentCode;
            runLogInfo.RunType = "CCD数量检测工位";

            runLogInfo.RunLog = "CCD数量检测任务开始";
            //await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);

            if (plcConn == null)
            {
                //runLogInfo.RunLog = $"获取连接({writeBo.PlcConnectionID})失败";
                //await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);
                _LogUtil.Error($"CCD数量检测工位：托盘【{plcMessage.PalletBarcode}】在设备【{plcMessage.EquipmentCode}】CCD数量检测工位：plc连接池无数据");
                return;
            }

            #region 读写交互准备
            //验证plc是否在线
            var plcIPStates = await _IPlcConnectionStateInfoRepository.GetFirstAsync(l => l.PlcConnectionID == plcMessage.PlcConnectionID && l.Connected == true);
            if (plcIPStates == null)
            {
                //runLogInfo.RunLog = $"{plcConn.IP}plc已离线";
                //await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);
                _LogUtil.Error($"CCD数量检测工位：托盘【{plcMessage.PalletBarcode}】在设备【{plcMessage.EquipmentCode}】CCD数量检测工位：请求分配失败：{plcConn.IP}:plc已离线");
                return;
            }

            var objectType = typeof(PlanarGeneralWriteWcsAction).Name;


            //获取写入PLC的DB地址根据设备号和类对象
            var writeConfig = await _PlcWriteDbInfoRepository.GetFirstAsync(s => s.EquipmentCode == plcMessage.EquipmentCode
            && s.ObjectType == objectType);

            if (writeConfig == null)
            {
                //runLogInfo.RunLog = $"获取PLC写入配置失败";
                //await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);
                _LogUtil.Error($"CCD数量检测工位：托盘【{plcMessage.PalletBarcode}】在设备【{plcMessage.EquipmentCode}】CCD数量检测工位获取PLC写入配置失败！请检查写DB配置！");
                return;
            }

            long plcID = wcsMessage.PlcConnectionID;
            writeBo = new PlanarGeneralWriteWcsAction(
                    writeConfig.PlcConnectionId,
                    writeConfig.ID,
                    writeConfig.DbCode,
                    writeConfig.DbStart,
                    objectType,
                    writeConfig.EquipmentCode.ToInt32(),
                    plcMessage.ActionType,
                    toEquipmentCode: plcMessage.EquipmentCode.ToInt32(),
                    0,//任务号
                    palletBarcode: plcMessage.PalletBarcode,
                    palletType: plcMessage.PalletType,
                    0
                );
            //var plcCon = _PlcConnectionPool.S7GetWritePlcConnection(writeBo.PlcConnectionID);//wcs写入连接
            //if (plcCon == null)
            //{
            //    runLogInfo.RunLog = $"获取连接({plcConn.IP})失败";
            //    await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);

            //    return;
            //}


            //校验plc信息是否有托盘码
            if (string.IsNullOrEmpty(plcMessage.PalletBarcode) || plcMessage.PalletBarcode.Length != 10)
            {
                writeBo.AlrmCode = 102;
                writeBo.ActionType = 99;
                await plcConn.WriteDbAsync(writeBo.DbCode, writeBo.DbStart, writeBo.Deserialize());
                _IRedisHelper.SetStringKey($"PLC-{plcMessage.EquipmentCode}", plcMessage.EquipmentCode.ToString() + plcMessage.AlrmCode, TimeSpan.FromSeconds(10));
                return;
            }

            //托盘类型
            switch (writeBo.PalletBarcode.Substring(1, 1))
            {
                case "A":
                    writeBo.PalletType = 2;
                    break;
                case "B":
                    writeBo.PalletType = 1;
                    break;
                case "C":
                    writeBo.PalletType = 3;
                    break;
            }

            #endregion

            #region 托盘号不存在&校验电池数量
            WMSApiDomain.WebApi.HeaderResult<bool> flag = new();
            try
            {

                //获取检测电池的数量
                if (plcMessage.ActionType == 4)
                    flag = await WCSMessageWithWMSApi.WCSGetBatteryCountAsync(plcMessage.PalletBarcode, plcMessage.Reserve, plcMessage.EquipmentCode);
                else
                    flag = await WCSMessageWithWMSApi.WCSGetBatteryCountAsync(plcMessage.PalletBarcode, 0, plcMessage.EquipmentCode);//4楼车间校验组盘信息

                if (!flag.IsSucceed)
                {
                    if(plcMessage.ActionType == 40)
                    {
                        //runLogInfo.RunLog = $"托盘校验失败:{flag.Message},PLC写入报文内容： {JsonConvert.SerializeObject(writeBo)}";
                        writeBo.AlrmCode = 14;
                        writeBo.ActionType = 41;
                        //await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);
                        var writeRes = await plcConn.WriteDbAsync(writeBo.DbCode, writeBo.DbStart, writeBo.Deserialize());
                        _LogUtil.Error($"CCD数量检测工位：托盘【{plcMessage.PalletBarcode}】在设备【{plcMessage.EquipmentCode}】托盘校验失败:{flag.Message},PLC写入报文内容： {JsonConvert.SerializeObject(writeBo)}！");
                        return;
                    }
                    else
                    {
                        //runLogInfo.RunLog = $"WMS接口CCD数量检测异常:{flag.Message},PLC写入报文内容： {JsonConvert.SerializeObject(writeBo)}";
                        //await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);
                        writeBo.AlrmCode = 124;
                        writeBo.ActionType = 5;
                        var writeRes = await plcConn.WriteDbAsync(writeBo.DbCode, writeBo.DbStart, writeBo.Deserialize());
                        _IRedisHelper.SetStringKey($"PLC-{plcMessage.EquipmentCode}", plcMessage.EquipmentCode.ToString() + plcMessage.AlrmCode, TimeSpan.FromSeconds(10));
                        _LogUtil.Error($"CCD数量检测工位：托盘【{plcMessage.PalletBarcode}】在设备【{plcMessage.EquipmentCode}】WMS接口CCD数量检测异常:{flag.Message},PLC写入报文内容： {JsonConvert.SerializeObject(writeBo)}！");
                        return;
                    }                        

                }
                else
                {
                    if (plcMessage.ActionType == 40)
                    {
                        var writeRes = await plcConn.WriteDbAsync(writeBo.DbCode, writeBo.DbStart, writeBo.Deserialize());
                        if (!writeRes)
                        {
                            //runLogInfo.RunLog = $"PLC(IP{plcConn.IP},写入报文失败";
                            //await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);

                            _LogUtil.Error($"CCD数量检测工位：托盘【{plcMessage.PalletBarcode}】CCD数量检测工位，PLC设备【{plcMessage.EquipmentCode}】,PLC(IP{plcConn.IP},写入报文失败");
                            return;
                        }

                        runLogInfo.RunLog = $"CCD数量检测工位：托盘【{plcMessage.PalletBarcode}】CCD数量检测工位，PLC设备【{plcMessage.EquipmentCode}】CCD数量检测工位成功，写入报文成功！报文内容：{JsonConvert.SerializeObject(writeBo)}";
                        await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);
                        return;
                    }
                }
            }
            catch (Exception ex)
            {

                //runLogInfo.RunLog = $"CCD数量检测异常，连接失败";
                //await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);
                writeBo.AlrmCode = 125;
                writeBo.ActionType = 99;
                var writeRes = await plcConn.WriteDbAsync(writeBo.DbCode, writeBo.DbStart, writeBo.Deserialize());
                _IRedisHelper.SetStringKey($"PLC-{plcMessage.EquipmentCode}", plcMessage.EquipmentCode.ToString() + plcMessage.AlrmCode, TimeSpan.FromSeconds(10));
                _LogUtil.Error($"CCD数量检测工位：托盘【{plcMessage.PalletBarcode}】在设备【{plcMessage.EquipmentCode}】WMS接口CCD数量检测异常:{ex.Message}！");
                return;
            }
            //由于WMS不下发任务，那么我直接以检测数量的托盘号为条件，搜索目标位置
            var route = await _WorkTaskInfoRepository.AsSugarClient().Queryable<RouteDetailInfo>()
                .Where(l => l.FromEquipment == plcMessage.EquipmentCode /*&& l.IsStart == true*/)
                .ToListAsync();

            #region wcs托盘上架任务已存在逻辑处理
            if (flag.IsSucceed)
            {
                //前面都通过，则任务开始
                //await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);
                //判断设备在wcs是否已存在分配巷道任务
                var exp = Expressionable.Create<WorkTaskInfo>();
                exp.AndIF(true, (a) => a.PalletCode == plcMessage.PalletBarcode && (a.TaskState == EnumTaskState.Initial || a.TaskState == EnumTaskState.Executing));
                var wcsWorkTaskInfo = await _WorkTaskInfoRepository.GetFirstAsync(exp.ToExpression());
                //根据托盘是否存在其它的任务 && 起点位置是否相同判断，存在则写入正常报文Return
                if (wcsWorkTaskInfo != null /*&& wcsWorkTaskInfo.CurrentFromEquipment == plcMessage.EquipmentCode*/)
                {

                    //runLogInfo.RunLog = $"请求分配重复:任务号：{wcsWorkTaskInfo.TaskCode}入库任务已存在";
                    //await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);
                    _LogUtil.Error($"CCD数量检测工位：托盘【{plcMessage.PalletBarcode}】任务号：{wcsWorkTaskInfo.TaskCode}任务已存在");

                    //针对wcs任务为初始化的处理成执行中并同步更新wms任务状态
                    if (wcsWorkTaskInfo.TaskState == EnumTaskState.Initial || wcsWorkTaskInfo.TaskState == EnumTaskState.Executing)
                    {
                        wcsWorkTaskInfo.TaskState = EnumTaskState.Executing;
                        wcsWorkTaskInfo.UpdateTime = DateTime.Now;
                        wcsWorkTaskInfo.CurrentDetailTaskState = EnumDetailTaskState.Executing;
                        try
                        {
                            //同步更新wms任务状态
                            var flag1 = await WCSMessageWithWMSApi.WCSUpdateWMStaskStateAndProcessTaskStateAsync(wcsWorkTaskInfo.WmsTaskCode, (int)EnumTaskState.Executing);
                            if (flag1)
                            {
                                wcsWorkTaskInfo.UploadWmsState = EnumUploadWmsState.Succeed;
                                wcsWorkTaskInfo.UploadWmsTime = DateTime.Now;
                            }
                        }
                        catch (Exception ex)
                        {

                            //runLogInfo.RunLog = $"wms任务号{wcsWorkTaskInfo.TaskCode}同步状态更新失败";
                            //await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);
                            _LogUtil.Error($"CCD数量检测工位：托盘【{plcMessage.PalletBarcode}】同步状态更新报错：{ex.Message}");
                        }
                        //更新wcs任务状态为执行中
                        await _WorkTaskInfoRepository.UpdateAsync(wcsWorkTaskInfo);
                    }

                    //写入正常报文
                    writeBo.TaskCode = wcsWorkTaskInfo.TaskCode;
                    writeBo.PalletBarcode = wcsWorkTaskInfo.PalletCode;
                    writeBo.ToEquipmentCode = wcsWorkTaskInfo.CurrentToEquipment.ToInt32();
                    var writeBl = await plcConn.WriteDbAsync(writeBo.DbCode, writeBo.DbStart, writeBo.Deserialize());
                    if (!writeBl)
                    {
                        //runLogInfo.RunLog = $"请求分配重复:写入正常报文报文失败";
                        //await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);

                        _LogUtil.Error($"CCD数量检测工位：托盘【{plcMessage.PalletBarcode}】投料口申请任务重复，PLC设备【{plcMessage.EquipmentCode}】写入PLC失败！");
                        return;
                    }
                    else
                    {
                        runLogInfo.RunLog = $"CCD数量检测工位：托盘【{plcMessage.PalletBarcode}】投料口申请任务重复，PLC设备【{plcMessage.EquipmentCode}】写入PLC成功！写入报文：{JsonConvert.SerializeObject(writeBo)}";
                        await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);

                    }
                    return;
                }
            }
            #endregion

            //数量校验结果 写入PLC  2022-12-01 修改PLC只判断校验成功或者失败
            if (!flag.IsSucceed)
            {
                //检验失败 握手类型5  目标地址目标地址给不给都行 PLC不使用
                writeBo.ActionType = 5;
                writeBo.AlrmCode = 10;
                writeBo.ToEquipmentCode = route.Where(l => l.IsEnd == true).Select(l => l.ToEquipment).First().ToInt32();
                var writeRes = await plcConn.WriteDbAsync(writeBo.DbCode, writeBo.DbStart, writeBo.Deserialize());
                if (!writeRes)
                {
                    //runLogInfo.RunLog = $"分配目标位写入报文失败";
                    //await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);
                    _LogUtil.Error($"CCD数量检测工位：托盘【{plcMessage.PalletBarcode}】CCD数量检测工位检测失败，PLC设备【{plcMessage.EquipmentCode}】CCD数量检测工位写入报文失败");
                    return;
                }
                else
                {
                    runLogInfo.RunLog = $"CCD数量检测工位：托盘【{plcMessage.PalletBarcode}】CCD数量检测工位检测失败！，PLC设备【{plcMessage.EquipmentCode}】CCD数量检测工位写入报文成功,报文：{JsonConvert.SerializeObject(writeBo)}";
                    await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);
                }

                return;
            }
            else
            {
                //检验成功握手 4  目标地址给不给都行 PLC不使用
                writeBo.ActionType = 4;
                writeBo.ToEquipmentCode = route.Where(l => l.IsStart == true).Select(l => l.ToEquipment).First().ToInt32();
                var writeRes = await plcConn.WriteDbAsync(writeBo.DbCode, writeBo.DbStart, writeBo.Deserialize());

                if (!writeRes)
                {
                    _LogUtil.Error($"CCD数量检测工位：托盘【{plcMessage.PalletBarcode}】CCD数量检测工位检测成功，PLC设备【{plcMessage.EquipmentCode}】CCD数量检测工位写入报文失败");
                    return;
                }
                else
                {
                    runLogInfo.RunLog = $"CCD数量检测工位：托盘【{plcMessage.PalletBarcode}】CCD数量检测工位检测成功！，PLC设备【{plcMessage.EquipmentCode}】CCD数量检测工位写入报文成功,报文：{JsonConvert.SerializeObject(writeBo)}";
                    await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);
                }
                //runLogInfo.RunLog = $"视觉检测数量正确";
                //await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);
            }

            #endregion



            #region 新建任务
            //WmsTaskInfoDto workTaskDto = null;
            //try
            //{
            //    //向wms读取检测数量到扫码任务
            //    workTaskDto = await WCSMessageWithWMSApi.WCSCreatCheckCountWMSTaskAsync(plcMessage.PalletBarcode, plcMessage.EquipmentCode);
            //}
            //catch (Exception ex)
            //{
            //    _LogUtil.Error($"数量检测到扫码分配巷道任务失败：向Wms请求任务失败，托盘号{plcMessage.PalletBarcode}，设备编号{plcMessage.EquipmentCode}！异常：{ex.ToString()}");
            //}

            ////wms请求失败处理 写入5报警握手类型
            //if (workTaskDto == null)
            //{
            //    _LogUtil.Error($"[平面设备数量检测报文服务]请求扫码巷道分配路径失败：Wms请求任务失败，托盘号{plcMessage.PalletBarcode}，设备编号{plcMessage.EquipmentCode}！");
            //    writeBo.ActionType = 5;
            //    var writeBl = await plcConn.WriteDbAsync(writeBo.DbCode, writeBo.DbStart, writeBo.Deserialize());
            //    if (writeBl == false)
            //    {
            //        _LogUtil.Error($"[平面设备数量检测报文服务]请求扫码巷道分配路径失败：PLC(IP{plcConn.IP},设备编号{writeBo.EquipmentCode})写入报文失败");
            //    }
            //    else
            //    {
            //        _LogUtil.Info($"[平面设备数量检测报文服务]请求扫码巷道分配路径发送报文成功  PLCId:{writeBo.PlcConnectionID} DBId:{writeBo.PlcWriteDbID}  设备编号{writeBo.EquipmentCode} WCS握手{writeBo.ActionType}");
            //    }
            //    return;
            //}


            ////WorkTaskInfo数据补全
            //var workTaskInfo = new WorkTaskInfo();
            //long id = _Snowflake.GetId();
            //workTaskInfo.ID = id;

            ////wcs任务code从wmstaskcode日开始截取
            //int.TryParse(workTaskDto.TaskCode.ToString().Substring(6), out var wcsTaskCode);
            //workTaskInfo.TaskCode = wcsTaskCode;

            ////wms赋值
            //workTaskInfo.WmsTaskCode = workTaskDto.TaskCode;
            //workTaskInfo.DependWmsTaskCode = workTaskDto.DependWMSTaskCode;
            //workTaskInfo.TaskType = Enum.Parse<EnumTaskType>(workTaskDto.TaskType.ToString());

            //workTaskInfo.WmsFromPosition = workTaskDto.StartPosition;//设备
            //workTaskInfo.WmsToPosition = workTaskDto.EndPosition;
            //workTaskInfo.WmsFromStation = workTaskDto.FromStation;//工站
            //workTaskInfo.WmsToStation = workTaskDto.ToStation;

            //workTaskInfo.TaskProcessState = EnumTaskProcessState.Initial;//任务执行状态
            //workTaskInfo.TaskState = EnumTaskState.Executing;//任务状态
            //workTaskInfo.Priority = workTaskDto.Priority;

            ////托盘条码
            //workTaskInfo.PalletCode = plcMessage.PalletBarcode;


            ////获取配置工位路径信息
            //var routeConfigExp = Expressionable.Create<RouteInfo>();
            //routeConfigExp.AndIF(true, (a) => a.FromStation == workTaskInfo.WmsFromStation && a.ToStation == workTaskInfo.WmsToStation);
            //var routeInfo = await _WorkTaskInfoRepository.AsSugarClient()
            //    .Queryable<RouteInfo>()
            //    .Where(routeConfigExp.ToExpression())
            //    .Select((a) => new RouteInfo()
            //    {
            //        ID = a.ID,
            //        //不必要
            //        FromStation = a.FromStation,
            //        ToStation = a.ToStation,
            //    }).FirstAsync();
            //if (routeInfo == null)
            //{
            //    _LogUtil.Info($"[平面设备数量检测报文服务]请求扫码巷道分配路径处理失败：设备编号{writeBo.EquipmentCode}巷道路径信息，起始工位{workTaskInfo.WmsFromStation}目标工位{workTaskInfo.WmsToStation}获取失败");
            //    return;
            //}

            ////巷道详情信息获取
            //var routeDetailConfigExp = Expressionable.Create<RouteDetailInfo>();
            //routeDetailConfigExp.AndIF(true, (a) => a.RouteID == routeInfo.ID && a.IsStart);
            //var routeDetailInfo = await _WorkTaskInfoRepository.AsSugarClient()
            //    .Queryable<RouteDetailInfo>()
            //    .Where(routeDetailConfigExp.ToExpression())
            //    .Select((a) => new
            //    {
            //        ID = a.ID,
            //        RouteID = a.RouteID,
            //        FromCargo = a.FromCargo,
            //        ToCargo = a.ToCargo,
            //        DispatchType = a.DispatchType,
            //        FromEquipment = a.FromEquipment,
            //        ToEquipment = a.ToEquipment,

            //    }).FirstAsync();

            //if (routeDetailInfo == null)
            //{
            //    _LogUtil.Info($"[平面设备数量检测报文服务]请求扫码巷道分配路径处理失败：设备编号{writeBo.EquipmentCode}巷道路径详情配置信息起始工位{workTaskInfo.WmsFromStation}目标工位{workTaskInfo.WmsToStation}获取失败");
            //    return;
            //}

            ////起点终点信息由配置表中获取（从WMS中获取工位起始）
            //workTaskInfo.CurrentFromCargo = routeDetailInfo.FromCargo;
            //workTaskInfo.CurrentToCargo = routeDetailInfo.ToCargo;
            //workTaskInfo.RouteID = routeDetailInfo.RouteID;
            //workTaskInfo.CurrentRounteDetailID = workTaskDto.ID;
            //workTaskInfo.CurrentDispatchType = routeDetailInfo.DispatchType;

            ////起始设备位 
            //workTaskInfo.CurrentFromEquipment = workTaskInfo.WmsFromPosition; //WMS 作业实际起点设备
            //workTaskInfo.CurrentToEquipment = routeDetailInfo.ToEquipment;
            //workTaskInfo.CurrentDetailTaskState = EnumDetailTaskState.Executing;
            //#endregion

            //#region 如果WMS不下发任务
            //WorkTaskInfo taskInfo=new WorkTaskInfo();

            //var rounteInfo = await _WorkTaskInfoRepository.AsSugarClient().Queryable<RouteInfo, RouteDetailInfo>((l, m) =>
            //   new JoinQueryInfos(JoinType.Inner, l.ID == m.RouteID))
            //    .Where((l, m) => m.IsStart == true&&m.FromEquipment==plcMessage.EquipmentCode)
            //    .Select((l,m)=>m)
            //    .FirstAsync();

            //taskInfo.ID = _Snowflake.GetId();
            //taskInfo.RouteID = rounteInfo.RouteID;
            //taskInfo.Priority = 1;
            //taskInfo.PalletCode = plcMessage.PalletBarcode;

            ////起点终点信息由配置表中获取（从WMS中获取工位起始）
            //taskInfo.CurrentFromCargo = rounteInfo.FromCargo;
            //taskInfo.CurrentToCargo = rounteInfo.ToCargo;
            //taskInfo.RouteID = rounteInfo.RouteID;
            //taskInfo.CurrentRounteDetailID = rounteInfo.ID;
            //taskInfo.CurrentDispatchType = rounteInfo.DispatchType;

            ////起始设备位 
            //taskInfo.CurrentFromEquipment = plcMessage.EquipmentCode; //WMS 作业实际起点设备
            //taskInfo.CurrentToEquipment = rounteInfo.ToEquipment;
            //taskInfo.CurrentDetailTaskState = EnumDetailTaskState.Executing;



            //taskInfo.TaskCode = wcsTaskCode;

            ////wms赋值
            //taskInfo.WmsTaskCode =Convert.ToInt64( DateTime.Now.ToString("yyyyMMddhhmmssfff"));
            //taskInfo.DependWmsTaskCode = 0;
            //taskInfo.TaskType = 0;

            //taskInfo.WmsFromPosition = "88888888";//设备
            //taskInfo.WmsToPosition = "88888888";
            //taskInfo.WmsFromStation = "88888888";//工站
            //taskInfo.WmsToStation = "88888888";

            //taskInfo.CurrentCreateTime = DateTime.Now;
            //taskInfo.CurrentUpdateTime = DateTime.Now;
            //taskInfo.SaveTime = DateTime.Now;
            //taskInfo.UpdateTime = DateTime.Now;
            //#endregion

            //#region 同步更新wms任务状态&写入正常报文

            //try
            //{
            //    //同步更新wms任务状态为执行中
            //    var flag = await WCSMessageWithWMSApi.WCSUpdateWMStaskStateAndProcessTaskStateAsync(workTaskInfo.WmsTaskCode, (int)EnumTaskState.Executing);
            //    if (flag)
            //    {
            //        workTaskInfo.UploadWmsState = EnumUploadWmsState.Succeed;
            //        workTaskInfo.UploadWmsTime = DateTime.Now;

            //        taskInfo.UploadWmsState = EnumUploadWmsState.Succeed;
            //        taskInfo.UploadWmsTime = DateTime.Now;
            //    }
            //}
            //catch (Exception ex)
            //{
            //    _LogUtil.Error($"[平面设备数量检测报文服务]请求扫码巷道分配路径分配失败：设备编号{writeBo.EquipmentCode}wms任务号{workTaskInfo.TaskCode}同步状态更新失败{ex.ToString()}！");
            //}

            ////WorkTaskInfo数据插入
            //try
            //{
            //    workTaskInfo.CurrentCreateTime = DateTime.Now;
            //    workTaskInfo.CurrentUpdateTime = DateTime.Now;
            //    workTaskInfo.SaveTime = DateTime.Now;
            //    workTaskInfo.UpdateTime = DateTime.Now;
            //    var bl = await _WorkTaskInfoRepository.InsertAsync(workTaskInfo);

            //    var bl1 = await _WorkTaskInfoRepository.InsertAsync(taskInfo);
            //}
            //catch (Exception ex)
            //{
            //    _LogUtil.Error($"[平面设备扫码报文服务]wcs生成任务失败{ ex.Message}");
            //    return;
            //}


            ////写入正常报文到Plc
            //writeBo.TaskCode = workTaskInfo.TaskCode;
            //writeBo.ToEquipmentCode = workTaskInfo.CurrentToEquipment.ToInt32();

            //writeBo.TaskCode = taskInfo.TaskCode;
            //writeBo.ToEquipmentCode = taskInfo.CurrentToEquipment.ToInt32();
            //var writeResult = await plcConn.WriteDbAsync(writeBo.DbCode, writeBo.DbStart, writeBo.Deserialize());
            //if (writeResult == false)
            //{
            //    _LogUtil.Info($"[平面设备扫码报文服务]请求巷道分配处理失败：PLC(IP{plcConn.IP},设备编号{writeBo.EquipmentCode})写入报文失败");
            //    return;
            //}
            //else
            //{
            //    _LogUtil.Info($"AisleRequestService发送报文  PLCId:{writeBo.PlcConnectionID} DBId:{writeBo.PlcWriteDbID}  设备编号{writeBo.EquipmentCode} WCS握手{writeBo.ActionType}");
            //}
            #endregion

        }


    }
}
